package com.nopay.cdxphone.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.telecom.PhoneAccount;
import android.telecom.PhoneAccountHandle;
import android.telecom.TelecomManager;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.blankj.utilcode.util.RomUtils;
import com.blankj.utilcode.util.SPUtils;

import java.util.List;

import com.nopay.cdxphone.Constants;

/**
 * 呼叫转移工具
 */
public class CallTransferUtil {

    private static final int[] SIM_REVERSAL = {1, 0};

    /**
     * 开启呼叫转移
     * @param activity
     * @return
     */
    public static boolean open(Activity activity, String phoneForCallTransfer) {
        boolean isOpen = SPUtils.getInstance().getBoolean(Constants.SP_ENABLED_CALL_TRANSFER, false);
        if (isOpen) {
            int callTransferType = SPUtils.getInstance().getInt(Constants.SP_CALL_TRANSFER_TYPE, 2);
            int simIndex = SPUtils.getInstance().getInt(Constants.SP_CALL_SIM_INDEX, 0);

            int callTransferTypeCode = callTransferType == 1 ? 67 : 21;
            int simIndexForCallTransfer = callTransferType == 3 ? SIM_REVERSAL[simIndex] : simIndex;
            Intent intent = new Intent(Intent.ACTION_CALL);

            if(SPUtils.getInstance().getBoolean(Constants.SP_SIM_TELECOM, false)) {
                callTransferTypeCode = callTransferType == 1 ? 90 : 72;
                if(RomUtils.isXiaomi()) {
                    intent.setData(Uri.parse("tel:*" + callTransferTypeCode + phoneForCallTransfer));
                } else {
                    intent.setData(Uri.parse("tel:%2A" + callTransferTypeCode + phoneForCallTransfer));
                }
            } else {
                if(RomUtils.isXiaomi()) {
                    intent.setData(Uri.parse("tel:**" + callTransferTypeCode + "*" + phoneForCallTransfer + "%23"));
                } else {
                    intent.setData(Uri.parse("tel:%2A%2A" + callTransferTypeCode + "%2A" + phoneForCallTransfer + "%23"));
                }
            }
            if(callTransferType == 3) {
                assignSIM(activity, intent, simIndexForCallTransfer);
            }
            activity.startActivity(intent);
        }
        return isOpen;
    }

    /**
     * 关闭呼叫转移
     * @param activity
     */
    public static void close(Activity activity) {
        int callTransferType = SPUtils.getInstance().getInt(Constants.SP_CALL_TRANSFER_TYPE, 2);
        int simIndex = SPUtils.getInstance().getInt(Constants.SP_CALL_SIM_INDEX, 0);
        int callTransferTypeCode = callTransferType == 1 ? 67 : 21;
        int simIndexForCallTransfer = callTransferType == 3 ? SIM_REVERSAL[simIndex] : simIndex;

        Intent intent = new Intent(Intent.ACTION_CALL);
        if(SPUtils.getInstance().getBoolean(Constants.SP_SIM_TELECOM, false)) {
            callTransferTypeCode = callTransferType == 1 ? 900 : 720;
            if(RomUtils.isXiaomi()) {
                intent.setData(Uri.parse("tel:*" + callTransferTypeCode));
            } else {
                intent.setData(Uri.parse("tel:%2A" + callTransferTypeCode));
            }
        } else {
            if(RomUtils.isXiaomi()) {
                intent.setData(Uri.parse("tel:%23%23" + callTransferTypeCode + "%23"));
            } else {
                intent.setData(Uri.parse("tel:%23%23%20" + callTransferTypeCode + "%23"));
            }
        }
        if(callTransferType == 3) {
            assignSIM(activity, intent, simIndexForCallTransfer);
        }
        activity.startActivity(intent);
    }

    /**
     * 使用呼叫转移打电话
     * @param activity
     */
    public static void call(Activity activity, String phoneForCall) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        boolean isOpen = SPUtils.getInstance().getBoolean(Constants.SP_ENABLED_CALL_TRANSFER, false);
        if (isOpen) {
//            String sim1Number = SPUtils.getInstance().getString(Constants.SP_SIM1_PHONE_NUMBER, "");
//            String sim2Number = SPUtils.getInstance().getString(Constants.SP_SIM2_PHONE_NUMBER, "");
            String simNumber = SPUtils.getInstance().getString(Constants.SP_SIM_PHONE_NUMBER, "");
            intent.setData(Uri.parse("tel:" + simNumber));

            int callTransferType = SPUtils.getInstance().getInt(Constants.SP_CALL_TRANSFER_TYPE, 2);
            if(callTransferType == 3) {
                int simIndex = SPUtils.getInstance().getInt(Constants.SP_CALL_SIM_INDEX, 0);
                assignSIM(activity, intent, simIndex);
            }
        } else {
            intent.setData(Uri.parse("tel:" + phoneForCall));
        }
        activity.startActivity(intent);
    }

    public static final String[] DUAL_SIM_TYPES = {"subscription", "Subscription", "com.android.phone.extra.slot", "phone", "com.android.phone.DialingMode", "simId", "simnum", "phone_type", "simSlot"};

    /**
     * 指定使用的SIM
     * @param activity
     * @param intent
     * @param simIndex
     */
    private static void assignSIM(Activity activity, Intent intent, int simIndex) {
        if(RomUtils.isHuawei() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
            for (String dualSimType : DUAL_SIM_TYPES) {
                intent.putExtra(dualSimType, simIndex);
            }
        } else if(RomUtils.isVivo() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
            for (String dualSimType : DUAL_SIM_TYPES) {
                intent.putExtra(dualSimType, simIndex);
            }
        } else {
            if(getSIMStatus(activity) < 2) return;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                TelecomManager telManager = (TelecomManager) activity.getSystemService(Context.TELECOM_SERVICE);
                if (telManager != null) {
                    if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                        List<PhoneAccountHandle> phoneAccountHandleList = telManager.getCallCapablePhoneAccounts();
                        if (phoneAccountHandleList.size() > simIndex) {
                            PhoneAccountHandle phoneAccountHandle = phoneAccountHandleList.get(simIndex);
                            if (phoneAccountHandle != null)
                                intent.putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, phoneAccountHandle);
                        }
                    }
                }
            }
        }
    }

    private static final String[] PHONE_ACCOUNT_SHORT_DESCRIPTION_LIST = {"SIM 卡，插槽：0", "SIM 卡，插槽：1", "只能拨打紧急呼救电话"};
    private static final String[] PHONE_ACCOUNT_SHORT_DESCRIPTION_LIST_VIVO = {"SIM card，slot：0", "SIM card，slot：1", "只能拨打紧急呼救电话"};

    /**
     * 获取SIM状态
     * @param activity
     * @return
     */
    public static int getSIMStatus(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            TelecomManager telManager = (TelecomManager) activity.getSystemService(Context.TELECOM_SERVICE);
            if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                List<PhoneAccountHandle> phoneAccountHandleList = telManager.getCallCapablePhoneAccounts();
                for (int i = phoneAccountHandleList.size() - 1; i >= 0; i--) {
                    PhoneAccountHandle phoneAccountHandle = phoneAccountHandleList.get(i);
                    if(phoneAccountHandle.getId() == null || "".equals(phoneAccountHandle.getId()) || "null".equals(phoneAccountHandle.getId())) {
                        phoneAccountHandleList.remove(i);
                    }
                }
                if(phoneAccountHandleList.size() >= 2) return 2;
                
                for (PhoneAccountHandle phoneAccountHandle : phoneAccountHandleList) {
                    PhoneAccount phoneAccount = telManager.getPhoneAccount(phoneAccountHandle);
                    CharSequence charSequence = phoneAccount.getShortDescription();
                    Log.e("SIM_INFO", charSequence.toString());
                    char slotChar = charSequence.charAt(charSequence.length() - 1);
                    String slot = String.valueOf(slotChar);
                    if("0".equals(slot)) return 0;
                    if("1".equals(slot)) return 1;
                }
            }
        }
        return -1;
    }

    public static String getPhoneNumberBySubId(Activity activity, int subId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                SubscriptionInfo subscriptionInfo = SubscriptionManager.from(activity).getActiveSubscriptionInfo(subId);
                if(subscriptionInfo != null) {
                    String number = subscriptionInfo.getNumber();
                    if(number == null || "".equals(number)) {
                        return getPhoneNumberByCallSetting();
                    }
                    return number;
                }
            }
        }
        return "";
    }

    public static String getPhoneNumberByCallSetting() {
        boolean isOpen = SPUtils.getInstance().getBoolean(Constants.SP_ENABLED_CALL_TRANSFER, false);
        if(isOpen) {
            if(SPUtils.getInstance().getInt(Constants.SP_CALL_TRANSFER_TYPE, 2) == 3) {
                int simIndex = SPUtils.getInstance().getInt(Constants.SP_CALL_SIM_INDEX, 0);
                return SPUtils.getInstance().getString(simIndex == 0 ? Constants.SP_SIM1_PHONE_NUMBER : Constants.SP_SIM2_PHONE_NUMBER, "");
            }
            return SPUtils.getInstance().getString(Constants.SP_SIM_PHONE_NUMBER, "");
        }
        return "";
    }
}
